package com.norra.client.ui

import android.app.Activity
import android.content.Intent
import android.location.Address
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.Toolbar
import com.google.android.gms.maps.model.LatLng
import com.norra.base.api.ApiCallback
import com.norra.base.api.HError
import com.norra.base.api.WebService
import com.norra.base.api.entity.AddDeviceInfo
import com.norra.base.api.entity.BaseResponse
import com.norra.base.api.entity.Device
import com.norra.base.utils.Toaster
import com.norra.client.R
import com.norra.client.model.DeviceEvent
import kotlinx.android.synthetic.main.activity_add_device.*
import org.greenrobot.eventbus.EventBus

class AddDeviceActivity : BaseActivity() {

    private var isEdit: Boolean = false
    private var device: Device? = null
    private var latLng: LatLng? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isEdit = intent.getBooleanExtra("is_edit", false)
        setContentView(R.layout.activity_add_device)
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        toolbar.setNavigationOnClickListener {
            onBackPressed()
        }

        btn_add.setOnClickListener {

            var name = edit_tag.text.toString().trim()
            var address = edit_address.text.toString().trim()
            var postcode = edit_postcode.text.toString().trim()
            if (name.isEmpty()) {
                Toaster.shortToast("Input tag")
                return@setOnClickListener
            }
            if (address.isEmpty()) {
                Toaster.shortToast("Input address")
                return@setOnClickListener
            }
            if (postcode.isEmpty()) {
                Toaster.shortToast("Input postcode")
                return@setOnClickListener
            }
            addDevice()
        }

        btn_location.setOnClickListener {
            val intent = Intent(AddDeviceActivity@ this, SelectGPSActivity::class.java)
            if (latLng != null) {
                intent.putExtra("lat_lng", latLng)
            }
            startActivityForResult(intent, 123)
        }

        if (isEdit) {
            device = intent.getSerializableExtra("device") as Device
            latLng = LatLng(device!!.lat!!, device!!.lng!!)
            edit_tag.setText(device!!.devName)
            edit_address.setText(device!!.address)
            edit_postcode.setText(device!!.district)
            btn_add.text = "SAVE"

            lat_layout.visibility = View.VISIBLE
            lng_layout.visibility = View.VISIBLE

            lat.text = device!!.lat.toString()
            lng.text = device!!.lng.toString()
        } else {
            btn_add.text = "ADD"
            lat_layout.visibility = View.GONE
            lng_layout.visibility = View.GONE
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        if (isEdit) {
            menuInflater.inflate(R.menu.menu_delete, menu)
        }
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {

        deleteDevice()
        return super.onOptionsItemSelected(item)
    }

    private fun deleteDevice() {
        val map = HashMap<String, String>()
        map["DevName"] = device!!.devName!!
        WebService.get().deleteVillaDevice(map).enqueue(object : ApiCallback<BaseResponse> {
            override fun onSuccess(response: BaseResponse) {
                finish()
                val event = DeviceEvent()
                event.devName = device!!.devName
                event.type = DeviceEvent.DELETE
                EventBus.getDefault().post(event)
            }

            override fun onError(error: HError) {

            }
        })

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 123 && resultCode == Activity.RESULT_OK) {

            val address = data!!.getParcelableExtra<Address>("address")
            if (address != null) {
                edit_address.setText(address.getAddressLine(0))
                edit_postcode.setText(address.thoroughfare)
            }
            latLng = data.getParcelableExtra("lat_lng") as LatLng
            if (latLng != null) {
                lat_layout.visibility = View.VISIBLE
                lng_layout.visibility = View.VISIBLE
                lat.text = latLng!!.latitude.toString()
                lng.text = latLng!!.latitude.toString()
            }
        }
    }


    private fun addDevice() {
        val devName = edit_tag.text.toString()
        val address = edit_address.text.toString()
        val deviceInfo = AddDeviceInfo()
        deviceInfo.devName = devName
        deviceInfo.address = address
        deviceInfo.district = "District good"
        if (latLng != null) {
            deviceInfo.lat = latLng!!.latitude
            deviceInfo.lng = latLng!!.longitude
        } else {
            deviceInfo.lat = 23.123456778
            deviceInfo.lng = 118.12345678
        }
        WebService.get().addVillaDevice(deviceInfo).enqueue(object : ApiCallback<BaseResponse> {
            override fun onSuccess(response: BaseResponse) {
                Toaster.shortToast("Add success")
                sendAddDeviceEvent()
                finish()
            }

            override fun onError(error: HError) {
                Toaster.shortToast("Add fail")
            }

        })
    }

    private fun sendAddDeviceEvent() {
        val event = DeviceEvent()
        event.type = DeviceEvent.ADD
        EventBus.getDefault().post(event)
    }
}